﻿/***********************************************************
Copyright © 2015 Howyoung.
************************************************************
You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty.
************************************************************
您可以对所收受的本程序源代码，无论以何种媒介，复制与发布其完
整的复制物，然而您必须以显著及适当的方式在每一份复制物上发布
适当的著作权标示及无担保声明。
***********************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;

namespace MinecraftSavesBackup
{
    public partial class EnterSavesAddress : Form
    {
        public EnterSavesAddress()
        {
            InitializeComponent();
        }

        private void browseLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                savesAddressTextBox.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void savesAddressTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (savesAddressTextBox.Text.ToLower().Contains("saves"))
                {
                    //获取所有目录名
                    savesCheckedListBox.Items.Clear();
                    string dirPath = savesAddressTextBox.Text;
                    List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
                    foreach (string folder in dirs)
                    {
                        savesCheckedListBox.Items.Add(folder.Substring(folder.LastIndexOf("\\") + 1));
                    }
                    if (savesCheckedListBox.Items.Count == 0)
                    {
                        savesCheckedListBox.Items.Clear();
                        savesCheckedListBox.Items.Add("未找到存档。");
                    }
                    else
                    {
                        savesLabel.Text = "包含的游戏存档 (共计" + Convert.ToString(savesCheckedListBox.Items.Count) + "个)";
                    }
                }
                else
                {
                    savesCheckedListBox.Items.Clear();
                    savesCheckedListBox.Items.Add("您指定的不是存档文件夹，请重试。");
                }
            }
            catch (Exception)
            {
                savesCheckedListBox.Items.Clear();
                savesCheckedListBox.Items.Add("出现错误，请检查目录是否存在。");
            }
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            Welcome Welcome = new Welcome();
            Welcome.Show();
            Close();
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            //检查有无异常选择项
            if (savesCheckedListBox.CheckedItems.Count == 0)
            {
                MessageBox.Show("请选择您要备份的游戏存档。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (savesCheckedListBox.Items.Contains("您指定的不是存档文件夹，请重试。"))
            {
                MessageBox.Show("您指定的不是存档文件夹，请重试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (savesCheckedListBox.Items.Contains("出现错误，请检查目录是否存在。"))
            {
                MessageBox.Show("出现错误，请检查目录是否存在。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (savesCheckedListBox.Items.Contains("未找到存档。"))
            {
                MessageBox.Show("未找到存档。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                try
                {
                    //禁用所有按钮
                    nextButton.Enabled = false;
                    nextButton.Text = "请稍后(0%)";
                    backButton.Enabled = false;
                    browseLinkLabel.Enabled = false;
                    //写入SaveAddress
                    string savesAddress = savesAddressTextBox.Text;
                    if (savesAddress.EndsWith("\\"))
                    {
                        Properties.Settings.Default.SaveAddress = savesAddressTextBox.Text;
                    }
                    else
                    {
                        Properties.Settings.Default.SaveAddress = savesAddressTextBox.Text + "\\";
                    }
                    //写入BackupDirectoryAddress
                    Properties.Settings.Default.BackupDirectoryAddress.Clear();
                    foreach (object item in savesCheckedListBox.CheckedItems)
                    {
                        string backupDirectoryAddress;
                        if (savesAddress.EndsWith("\\"))
                        {
                            backupDirectoryAddress = savesAddress + item;
                        }
                        else
                        {
                            backupDirectoryAddress = savesAddress + "\\" + item;
                        }
                        Properties.Settings.Default.BackupDirectoryAddress.Add(backupDirectoryAddress);
                        backupDirectoryAddress = null;
                    }
                    //保存设置
                    Properties.Settings.Default.Save();
                    backgroundWorker.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    HandlingErrors.ErrorMessage(ex, "请再试一次。");
                    HandlingErrors.Record(ex);
                }
            }
        }

        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                double count = 0;
                double all = Properties.Settings.Default.BackupDirectoryAddress.Count;
                Properties.Settings.Default.MD5.Clear();
                foreach (string directoryName in Properties.Settings.Default.BackupDirectoryAddress)
                {
                    DirectoryInfo directory = new DirectoryInfo(directoryName);
                    //遍历文件
                    foreach (FileInfo files in directory.GetFiles("*", SearchOption.AllDirectories))
                    {
                        //计算MD5
                        string fileName = files.FullName;
                        string md5 = "";
                        byte[] hashValue;
                        FileStream fileStream = null;
                        System.Security.Cryptography.MD5CryptoServiceProvider md5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider();
                        fileStream = new FileStream(fileName.Replace("\"", ""), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        hashValue = md5CSP.ComputeHash(fileStream);
                        fileStream.Close();
                        md5 = BitConverter.ToString(hashValue);
                        md5 = md5.Replace("-", "");
                        Properties.Settings.Default.MD5.Add("{" + fileName + "}" + md5);
                    }
                    count++;
                    backgroundWorker.ReportProgress(Convert.ToInt32(count / all * 100));
                }
            }
            catch (Exception ex)
            {
                HandlingErrors.ErrorMessage(ex, "请再试一次。");
                HandlingErrors.Record(ex);
            }
        }

        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            nextButton.Text = "请稍后(" + Convert.ToString(e.ProgressPercentage) + "%)";
        }

        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            nextButton.Enabled = true;
            nextButton.Text = "下一步(&N)";
            backButton.Enabled = true;
            browseLinkLabel.Enabled = true;
            EnterBackupAddress EnterBackupAddress = new EnterBackupAddress();
            EnterBackupAddress.Show();
            Close();
        }
    }
}
